package com.ptsz.mydatbase.utils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.ptsz.mydatbase.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class DbManage {

    private final int DATABASE_VERSION = 3;//最初版本为1
    private final int BUFFER_SIZE = 400000;

    public static String dbPath;
    public static String dbName = "collect_back.gpkg";

    private SQLiteDatabase database;
    private Context context;


    public DbManage(Context context) {
        this.context = context;
        dbPath = Environment.getDataDirectory().getAbsolutePath() + File.separator + "data" + File.separator + "com.ptsz.mydatbase";
    }

    public void openDatabase() {
        this.database = this.openDatabase(dbPath + "/" + dbName);
        updateDatabase(database.getVersion(), DATABASE_VERSION);
    }

    public SQLiteDatabase getDatabase() {
        return database;
    }


    private SQLiteDatabase openDatabase(String dbfile) {
        try {
            File f = new File(dbPath);
            if (!f.exists()) {
                boolean mkdir = f.mkdir();
                System.out.println(mkdir);
                if (!mkdir) {
                    boolean mkdirs = f.mkdirs();
                    System.out.println(mkdirs);
                }
            }
            File file = new File(dbfile);
            if (!(file.exists())) {
                file.createNewFile();
                InputStream is = this.context.getResources().openRawResource(R.raw.collect_back); //欲导入的数据库

                FileOutputStream fos = new FileOutputStream(dbfile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
                SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
                        null);
                db.setVersion(DATABASE_VERSION);

                return db;
            }
            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
                    null);

            return db;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void updateDatabase(int oldVersion, int newVersion) {
        if (oldVersion >= newVersion) {
            return;
        }
        updateDB();
        database.setVersion(newVersion);
    }

    private void updateDB() {
        closeDatabase();
        File db = new File(dbPath + "/" + dbName);
        db.delete();
        openDatabase();
    }

    public void closeDatabase() {
        this.database.close();
    }
}
